package com.jck.wx.util;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.UUID;

import org.apache.commons.codec.binary.Base64;

import com.jck.dplus.common.utils.util.ChkUtil;

import net.sf.jsqlparser.statement.replace.Replace;

/**
 * 将图片转换为Base64<br>
 * 将base64编码字符串解码成img图片
 * 
 * @author Administrator
 *
 */
public class Img2Base64Util {

	/**
	 * 将图片转换成Base64编码
	 * 
	 * @param imgFile 待处理图片
	 * @return
	 */
	public static String getImgStr(String imgFileFullName) {
		String base64ImgStr = null;
		// 将图片文件转化为字节数组字符串，并对其进行Base64编码处理
		InputStream in = null;
		byte[] data = null;
		// 读取图片字节数组
		try {
			in = new FileInputStream(imgFileFullName);
			data = new byte[in.available()];
			in.read(data);
			in.close();
			base64ImgStr = new String(Base64.encodeBase64(data));
		} catch (Exception e) {
			e.printStackTrace();
		}

		return base64ImgStr;
	}
	public static String getImgStr(InputStream in) {
		String base64ImgStr = null;
		// 将图片文件转化为字节数组字符串，并对其进行Base64编码处理
		byte[] data = null;
		// 读取图片字节数组
		try {
			data = new byte[in.available()];
			in.read(data);
			in.close();
			base64ImgStr = new String(Base64.encodeBase64(data));
		} catch (Exception e) {
			e.printStackTrace();
		}

		return base64ImgStr;
	}
	public static String getImgStr(byte[] data) {
		String base64ImgStr = null;
		// 读取图片字节数组
		try {
			base64ImgStr = new String(Base64.encodeBase64(data));
		} catch (Exception e) {
			e.printStackTrace();
		}

		return base64ImgStr;
	}

	/**
	 * 对字节数组字符串进行Base64解码并生成图片
	 * 
	 * @param base64ImgStr
	 * @param saveImgFileFullName
	 * @return
	 */
	public static boolean generateImage(String base64ImgStr, String saveImgFileFullName) {
		//
		if (base64ImgStr == null) // 图像数据为空
			return false;

		try {
			// Base64解码
			byte[] b = Base64.decodeBase64(base64ImgStr);
			for (int i = 0; i < b.length; ++i) {
				if (b[i] < 0) {// 调整异常数据
					b[i] += 256;
				}
			}
			saveImgFileFullName=ChkUtil.isEmpty(saveImgFileFullName)?UUID.randomUUID().toString().replace("-", "")+".jpg":saveImgFileFullName;
			// 生成jpeg图片
			OutputStream out = new FileOutputStream(saveImgFileFullName);
			out.write(b);
			out.flush();
			out.close();
			return true;
		} catch (Exception e) {
			return false;
		}
	}
}